import { customBaseQuery } from './config'
import { SignInFormValues } from '../components/forms/signInForm'
import { SignUpFormValues } from '../components/forms/signUpForm'
import { TUser } from '../store/types'
import { createApi } from '@reduxjs/toolkit/query/react'

type TBEUserAuthResponse = {
	data: TUser
	token: string
}

export type TEditUserRequest = {
	name: string
	about: string
}

export const userApiSlice = createApi({
	reducerPath: 'userApiSlice',
	baseQuery: customBaseQuery,
	endpoints: (builder) => ({
		// Аутентификация
		signIn: builder.mutation<TBEUserAuthResponse, SignInFormValues>({
			query: (authUser) => ({
				url: '/signin',
				method: 'POST',
				body: authUser,
			}),
		}),
		// Регистрация
		signUp: builder.mutation<TUser, SignUpFormValues>({
			query: (userAuth) => ({
				url: '/signup',
				method: 'POST',
				body: userAuth,
			}),
		}),
		// Изменение данных пользователя
		editUser: builder.mutation<TUser, TEditUserRequest>({
			query: (params) => ({
				url: '/users/me',
				method: 'PATCH',
				body: params,
			}),
		}),
	}),
})

export const { useSignInMutation, useSignUpMutation, useEditUserMutation } =
	userApiSlice
